package com.deuwise.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.common.utils.*;
import com.deuwise.common.utils.authorize.LicenseCode;
import com.deuwise.common.utils.cache.Cache;
import com.deuwise.config.oauth2.CheckAuthorizeCode;
import com.deuwise.system.entity.AuthorizeDo;
import com.deuwise.system.entity.KeyPairDo;
import com.deuwise.system.entity.TokenVO;
import com.deuwise.system.entity.from.PassConfigForm;
import com.deuwise.system.entity.from.SysLoginForm;
import com.deuwise.system.entity.from.UserLogoutDTO;
import com.deuwise.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author chenshun
 * email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController()
@RequestMapping("/sys")
@Api(tags = "登录模块", description = "")
public class SysLoginController extends AbstractController {

	@Autowired
	private SysUserService sysUserService;

    @Autowired
    private KeyPairDoService keyPairDoService;

    /** 公钥 */
    private static final String PUBLIC_KEY = "RSAPublicKey";
    /** 私钥 */
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    @Value("${bootsystem.isrsa}")
    private boolean isrsa;


    @Value("${bootsystem.vaildCode}")
	private  boolean vaildCode;
	/**
	 * 登录
	 */
	@ApiOperation("登录")
	@PostMapping("/login")
	@ResponseBody
	public Result<TokenVO> login(@RequestBody SysLoginForm form ,HttpServletRequest request){
		if(vaildCode){
			if(StringUtils.isBlank(form.getCode())){
				return  Result.build(500,"验证码不能为空");
			}else{
				String ip = request.getRemoteAddr();
				Object object= Cache.get(ip+"_VerifyCode");
				String redisCode = (String)object;
				if (form.getCode() != null && !"".equals(form.getCode()) && redisCode != null && !"".equals(redisCode)) {
					if (form.getCode().equalsIgnoreCase(redisCode)) {
						Cache.remove(ip+"_VerifyCode");
					} else {
						return  Result.build(500,"验证码不正确");
					}
				} else {
					return  Result.build(500,"验证码不正确");
				}
			}
		}
	    String password = form.getPassword();
	    String userName = form.getUsername();
		if(isrsa) {
		    /*启用加解密操作*/
            password = dataDecrypt(form.getPassword());
            if(StringUtils.isBlank(password)){
                /*为null，说明秘钥不对，也有可能是原始密码*/
                password = form.getPassword();
            }
            userName = dataDecrypt(form.getUsername());
            if(StringUtils.isBlank(userName)){
                userName = form.getUsername();
            }
        }
		TokenVO token = sysUserService.getToken(userName, Base64Utils.base64Encrypt(password),request.getHeader("User-Agent"));
		return Result.ok(token);
	//	return r;
	}
	@PostMapping("refresh")
	@ApiOperation("刷新token")
	public R refresh(@RequestParam String uname, @RequestBody final String refreshToken,HttpServletRequest request) {
		TokenVO token = sysUserService.refreshToken(uname, refreshToken,request.getHeader("User-Agent"));
		return R.ok(token);
	}
	@Autowired
	ConfigDoService configDoService;




	@PostMapping("logotu")
	@ApiOperation("注销token")
	public R logout(@RequestBody UserLogoutDTO dto) {
		sysUserService.logoutToken(dto.getToken(), dto.getRefreshToken());
		return R.ok();
	}

	@Autowired
	private AuthorizeDoService authorizeDoService;

	/**
	 * 单独的授权码保存接口，拿到传入的授权码后，保存到服务器的一个文件中
	 * @param code
	 * @return
	 */

	@ApiOperation("授权license")
	@CrossOrigin
	@GetMapping(value= "/importLicense")
	public Object importLicense(@ApiParam("code") String code){

	AuthorizeDo authorizeDo= authorizeDoService.selectOne(null);

	  if(authorizeDo!=null){
		authorizeDo.setCode(code);
		authorizeDoService.updateById(authorizeDo);
	  }else{
	  	authorizeDo=new AuthorizeDo();
	  	authorizeDo.setCode(code);
	  	authorizeDo.setCreate_time(new Date());
	  	authorizeDoService.insert(authorizeDo);
	  }
		boolean flag = false;
		try {
			//验证授权码是否正确
			flag = CheckAuthorizeCode.AuthorizeCode();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//授权成功
		if(flag){
			return R.ok("授权成功");
		}
		return R.ok("授权码错误");
	}

	@ApiOperation("获取申请码")
	@GetMapping(value= "/getApplyCode")
	public Result<JSONObject> getApplyCode(){
		String ApplyCode= LicenseCode.getApplyCode();
		AuthorizeDo authorizeDo= authorizeDoService.selectOne(null);
		String day="";
		if(authorizeDo!=null){
			 day=CheckAuthorizeCode.getEffective(authorizeDo.getCode());
		}
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("applyCode",ApplyCode);
		jsonObject.put("days",day);
		return Result.ok(jsonObject);
	}

	/**
	 * 密码解密
	 * @param value 加密后密码
	 * @return
	 */
	public String dataDecrypt(String value){
		/*获取私钥*/
		Wrapper<KeyPairDo> wrapper = new EntityWrapper<KeyPairDo>();
		wrapper.in("key", PRIVATE_KEY);
		KeyPairDo keyPair = keyPairDoService.selectOne(wrapper);
		if(null == keyPair){
			R.error(200,"秘钥不正确！");
		}
		String str = RSAUtils.decrypt(value,keyPair.getValue());
		return str;
	}
}
